package com.intretech.umsin.common.excel.service.impl;

import com.alibaba.excel.EasyExcel;
import com.intretech.umsin.common.excel.service.ExcelService;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @version V1.0
 * @ClassName: ExcelServiceForEasyImpl
 * @Description: ExcelServiceForEasyImpl 服务实现
 * @author: 李启联
 * @date: 2022-5-27 16:35
 * @Copyright: Copyright (c) 2022
 */
@Service("ExcelServiceForEasyImpl")
public class ExcelServiceForEasyImpl implements ExcelService {

    /**
     * 导出EXCEL
     *
     * @param list
     * @param clazz
     * @param sheetName
     * @return
     * @throws Exception
     */
    @Override
    public byte[] exportExcel(List<?> list, Class clazz, String sheetName) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            EasyExcel.write(outputStream,clazz).sheet(sheetName).doWrite(list);
            return outputStream.toByteArray();
        }catch (Exception e) {
            return new byte[0];
        }finally {
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }

    /**
     * 下载模板
     *
     * @param sheetName
     * @param clazz
     * @return
     */
    @Override
    public byte[] exportExcelTemplate(String sheetName, Class clazz) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            EasyExcel.write(outputStream,clazz).sheet(sheetName).doWrite(new ArrayList<>(0));
            return outputStream.toByteArray();
        }catch (Exception e) {
            return new byte[0];
        }finally {
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }
}
